import axios from 'axios';

// 取消重复请求
const CancelToken = axios.CancelToken;
// 用于存储每个请求的取消函数以及对应标识
const sources = [];


const url = import.meta.env;
class AxiosHttpRequest {
  baseURL;
  timeout;
  constructor() {
    this.baseURL = url.VITE_BASE_API;
    this.timeout = 5000;
  }
  // 配置参数
  getConfigParams(options) {
    const config = {
      baseURL: options.isLogin
        ? url.VITE_LOGIN_API
        : options.isFile
        ? url.VITE_UPLOAD
        : this.baseURL,
      timeout: this.timeout,
      headers: {},
    };
    return config;
  }
  // 拦截设置
  interceptors(instance, data) {
    // 请求拦截
    instance.interceptors.request.use(
      (config) => {
        // 取消重复请求
        // removeSource(config);
        config.cancelToken = new CancelToken((c) => {
          // 将取消函数存起来
          sources.push({ umet: config.url + '&' + config.method, cancel: c });
        });
        // 添加全局的loading..
        // 请求头携带token
        // config.headers['Authorization'] = 'Bearer ' + 'token666'
        config.headers = {
          'Content-Type': 'application/json;charset=utf-8',
          ...data.headers,
        };
        // get请求映射params参数
        if (config.method === 'get' && config.params) {
          let url = config.url + '?';
          for (const propName of Object.keys(config.params)) {
            const value = config.params[propName];
            const part = encodeURIComponent(propName) + '=';
            if (value !== null && typeof value !== 'undefined') {
              if (typeof value === 'object') {
                for (const key of Object.keys(value)) {
                  const params = propName + '[' + key + ']';
                  const subPart = encodeURIComponent(params) + '=';
                  url += subPart + encodeURIComponent(value[key]) + '&';
                }
              } else {
                url += part + encodeURIComponent(value) + '&';
              }
            }
          }
          url = url.slice(0, -1);
          config.params = {};
          config.url = url;
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      },
    );

    // 响应拦截
    instance.interceptors.response.use(
      (res) => {
        // 取消重复请求
        // removeSource(res.config);
        // 未设置状态码则默认成功状态
        const code = res.data['code'];
        const msg = res.data['message'] || '';
        if (res.config.url == '/subjectPlan/subjectCountExport') {
          const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });
          // const url = window.URL.createObjectURL(down);
          const downloadElement = document.createElement('a');
          const href = window.URL.createObjectURL(blob); //创建下载的链接
          downloadElement.href = href;
          downloadElement.download = '课题.xlsx'; //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(href); //释放掉blob对象
        } else if (res.config.url == '/base/file/download') {
          console.log(res);
          const blob = new Blob([res.data], { type: 'application/octet-stream;charset=utf-8' });
          const linkNode = document.createElement('a');
          const arr = res.config.params.filePath.split('/');
          linkNode.download = arr[arr.length - 1];
          linkNode.style.display = 'none';
          linkNode.href = window.URL.createObjectURL(blob);
          document.body.appendChild(linkNode);
          linkNode.click();
          window.URL.revokeObjectURL(linkNode.href);
          document.body.removeChild(linkNode);
        } else {
          if (code === '10000' || code === 200) {
            return Promise.resolve(res.data);
          } else {
            console.log(msg);
            return Promise.reject(res.data);
          }
        }
      },
      (error) => {
        console.log('err' + error);
        return Promise.reject(error);
      },
    );
  }

  request(options) {
    const instance = axios.create();
    options = Object.assign(this.getConfigParams(options), options);
    this.interceptors(instance, options);
    return instance(options);
  }
}

// 实例化请求类
const http = new AxiosHttpRequest();

export default http;
